package com.hhh.Filter;

import com.alibaba.fastjson2.JSON;
import com.hhh.Pojo.Result;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



 //要在启动类上加载@ServletComponentScan注解
//@WebFilter(urlPatterns = "/*")
    public class LoginCheckFilter implements Filter {

//        //     url匹配器
//        private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
//    你也可以写正则表达式去匹配，上一个项目就是这么写的

     private String regex = "/login";

        //    可以放行的url
        private static final String[] urlarr = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**"
        };

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        获取请求的url
            HttpServletRequest hSRequest = (HttpServletRequest) servletRequest;
            HttpServletResponse hSResponse = (HttpServletResponse) servletResponse;
            String url = String.valueOf(hSRequest.getRequestURL());
//        匹配url
//            for (String checkurl : urlarr) {
////            如果不需要处理，放行
//                if (ANT_PATH_MATCHER.match(checkurl, url) == true) {
//                    filterChain.doFilter(servletRequest, servletResponse);
//                    return;
//                }
//            }
            //判断URL是否是login,是否需要处理
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(url);
            String regexarr = "";
            while (matcher.find())
                regexarr = matcher.group();
//            无需处理
            if (regexarr.length() != 0) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
//        需要处理
//        判断是否登录
//        未登录
            if (hSRequest.getSession().getAttribute("employee") == null) {
                String notlogin = JSON.toJSONString(Result.error("NOTLOGIN"));
                hSResponse.getWriter().write(notlogin);
//            用了字节流要关流
                hSResponse.getWriter().close();
                return;
            }
//        已登录
            filterChain.doFilter(servletRequest, servletResponse);
        }

}
